package com.gs.demo.exception;

import com.gs.demo.controller.BaseController;
import com.gs.demo.enums.ResultCodeEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.multipart.MultipartException;

import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * @author 高尚 E-mail:
 * @date 2020年8月7日 上午9:23:04 类说明
 */
@RestControllerAdvice
public class GlobalExceptionHandler extends BaseController {
	private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

	@Autowired
	private com.gs.demo.conf.FileConfig FileConfig;

	/**
	 * 处理文件上传大小超限制
	 * 
	 * @param exception
	 * @return
	 */
	@ExceptionHandler(value = MultipartException.class)
	public String fileUploadExceptionHandler(MultipartException exception, HttpServletResponse response) {
		logger.error("Upload files up to "+FileConfig.getFileSize()+"M", exception);
		return getErrorResult(ResultCodeEnum.FILE_SIZE.getValue(),"Upload files up to "+FileConfig.getFileSize()+"M");
	}

	/**
	 * 参数校验异常
	 *
	 * @param exception
	 * @return
	 */
	@ExceptionHandler(value = MethodArgumentNotValidException.class)
	public String MethodArgumentNotValidException(MethodArgumentNotValidException exception, HttpServletResponse response) {
		logger.error(exception.getMessage());
		BindingResult result = exception.getBindingResult();
		final List<FieldError> fieldErrors = result.getFieldErrors();
		StringBuilder builder = new StringBuilder();

		for (FieldError error : fieldErrors) {
			builder.append( error.getDefaultMessage()+",");
		}
		return getErrorResult(ResultCodeEnum.VALID.getValue(),builder.toString());
	}

}
